<template>
	<swiper circular :indicator-dots="true" :autoplay="true" :interval="2000" :duration="500">
		<swiper-item v-for="(item, index) in images" :key="index" @tap="() => openLink(item.link)">
			<view class="swiper-item">
				<image class='swiper-img' :src="item.src" mode="aspectFill"></image>
			</view>
		</swiper-item>
	</swiper>
</template>

<script>
	export default {
		data() {
			return {
				images: [] // 初始化为空数组
			}
		},
		created() {
			this.fetchAdvertisements(); // 页面创建时获取广告数据
		},
		methods: {
			openLink(link) {
				if (link) {
					uni.navigateTo({
						url: `/pages/webview/webview?url=${encodeURIComponent(link)}`
					});
				}
			},
			fetchAdvertisements() {
				uni.request({
					url: this.$baseUrl + '/advertisement/getall', // 替换为你的后端接口
					method: 'GET',
					success: (res) => {
						if (res.data && res.data.code === 0) {
							this.images = res.data.data.map(ad => ({
								src: ad.picUrl, // 广告图片URL，确保字段名与返回数据一致
								link: ad.linkUrl // 广告链接URL，确保字段名与返回数据一致
							}));
						} else {
							console.error('获取广告数据失败', res);
						}
					},
					fail: (err) => {
						console.error('请求广告数据失败', err);
					}
				});
			}
		}
	}
</script>

<style scoped>
	swiper {
		width: 100%;
		height: 400rpx;
	}

	.swiper-img {
		width: 100%;
		height: 400rpx;
	}
</style>